package cn.listener;

import cn.TCSP;
import cn.util.TCUtil;
import cn.wetcland.dao.WetclandPlayerDao;
import cn.wetcland.panel.IntensifierPanel;
import cn.wetcland.panel.LevelerPanel;
import cn.wetcland.panel.RefinerPanel;
import cn.wetcland.pojo.WetclandPlayer;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.hover.content.Text;
import org.apache.ibatis.session.SqlSession;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.*;
import org.bukkit.inventory.ItemStack;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class PlayerEventListener implements Listener {

    @EventHandler
    public void playerJoinEvent(PlayerJoinEvent event) {
        event.setJoinMessage("");
        Player eventPlayer = event.getPlayer();
        // 登录到主城
        WetclandPlayer one = null;
        SqlSession sqlSession = null;
        try {
            eventPlayer.teleport(TCUtil.getLocationByNameInYaml("mainHall"));
            sqlSession = TCSP.getSqlSessionFactory().openSession(true);
            WetclandPlayerDao mapper = sqlSession.getMapper(WetclandPlayerDao.class);
            one = mapper.findOne(eventPlayer.getName());
        } catch (Exception exception) {
            eventPlayer.kickPlayer("§c登录发生异常，请重试！");
        }
        System.out.println(one);
        Map<String, Object> map = new HashMap<>();
        map.put("info", one);
        if (one == null) {
            eventPlayer.sendTitle(eventPlayer.getName(), "§b欢迎您加入Wetcland", 10, 10, 10);
            eventPlayer.sendMessage("§b---------------------");
            eventPlayer.sendMessage("§d请注册账号: 两种方式");
            BaseComponent[] baseComponents = new ComponentBuilder().append("§d方式①: 打开聊天栏用鼠标点击此处 http://www.wetcland.cn 官网注册§b(推荐)")
                    .event(new ClickEvent(ClickEvent.Action.OPEN_URL, "http://www.wetcland.cn"))
                    .event(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text("§a点击进入Wetcland官网")))
                    .create();
            eventPlayer.spigot().sendMessage(baseComponents);
            eventPlayer.sendMessage("§d方式②: 打开聊天栏 使用命令 \"/reg 密码 重复密码\" 进行注册");
            eventPlayer.sendMessage("§b---------------------");
            // 向新玩家播放励志BGM
            eventPlayer.playSound(eventPlayer.getLocation(), "wetcland.bgm_vision", 5f, 1f);
        } else {
            eventPlayer.sendTitle("§d欢迎回来", "", 1, 10, 1);
            eventPlayer.sendMessage("§b————————————————————————————");
            eventPlayer.sendMessage("§d打开聊天栏 使用命令 \"/login 密码\" 进行登录");
            eventPlayer.sendMessage("§b——————————————————————————————");
            eventPlayer.playSound(eventPlayer.getLocation(), "wetcland.gun_skull", 5f, 1f);
            // 更新等级血量饱食度
            TCUtil.updatePlayerHealthByLevel(eventPlayer, one.getLevel());
        }
        map.put("lr", false);
        map.put("wsb", null);
        TCSP.getPlayerAttr().put(eventPlayer.getName(), map);
        sqlSession.close();
    }

    @EventHandler
    public void playerMoveEvent(PlayerMoveEvent event) {
        Player eventPlayer = event.getPlayer();
        Map<String, Object> map = (Map<String, Object>) TCSP.getPlayerAttr().get(eventPlayer.getName());
        if (!(boolean) map.get("lr")) {
            // 如果未登录， 则玩家无法移动
            event.setCancelled(true);
        }
    }

    @EventHandler
    public void playerLevelEvent(PlayerQuitEvent event) {
        Player eventPlayer = event.getPlayer();
        event.setQuitMessage("");
        // 玩家退出停止计分板更新线程
        if (TCUtil.getAttrWetclandScoreBoard(eventPlayer.getName()) != null)
            TCUtil.getAttrWetclandScoreBoard(eventPlayer.getName()).turnOff();
        // 玩家退出移除维护
        if (TCSP.getPlayerAttr().get(eventPlayer.getName()) != null)
            TCSP.getPlayerAttr().remove(eventPlayer.getName());
    }

    @EventHandler
    public void playerChatEvent(AsyncPlayerChatEvent event) {
        // 如果不是异步事件 直接返回
        if (!event.isAsynchronous()) return;
        Player eventPlayer = event.getPlayer();
        if (!TCUtil.getAttrPlayerLRStatus(eventPlayer.getName())) {
            eventPlayer.sendMessage("§c请登录");
            event.setCancelled(true);
            return;
        }
        WetclandPlayer attrPlayer = TCUtil.getAttrPlayer(eventPlayer.getName());
        String memberTypeString = TCUtil.getMemberTypeString(attrPlayer.getMemberType());
        String stringWorld = TCUtil.getStringWorld(eventPlayer.getWorld().getName());
        String stringLevel = TCUtil.getStringLevel(attrPlayer.getLevel());
        String title = attrPlayer.getTitle() == null || attrPlayer.getTitle().equals("") ? "" : "§d[" + attrPlayer.getTitle() + "]";
        String stringMember = memberTypeString != null ? "§e[" + memberTypeString + "]" : "";
        String stringMarried = attrPlayer.isMarried() ? "§d[已婚]: " : ": ";
        event.setFormat("§a[" + stringWorld + "]" + "§d[" + stringLevel + "]" + title + stringMember + "§b[" + eventPlayer.getName() + "]" + stringMarried + "§r" + TCUtil.remakeDirtyStr(event.getMessage()));
    }

    @EventHandler
    public void playerClickEntityEvent(PlayerInteractEntityEvent event) {
        Player eventPlayer = event.getPlayer();
        Entity rightClicked = event.getRightClicked();
        if (rightClicked instanceof Player) {
            Player targetPlayer = (Player) rightClicked;
            Player player = event.getPlayer();
            if (TCUtil.getAttrPlayer(player.getName()).isMarried()) {
                player.sendMessage("§c你已经结婚了，收住你的幻想");
                return;
            }
            if (TCSP.getMarryAttr().get(player.getName()) != null) {
                player.sendMessage("§c您已发出了一个请求, 求婚间隔为 10 分钟");
                return;
            }
            ItemStack itemInMainHand = player.getInventory().getItemInMainHand();
            if (itemInMainHand.getItemMeta() != null && itemInMainHand.getItemMeta().getDisplayName().equals("§d求婚海螺")) {
                ComponentBuilder componentBuilder = new ComponentBuilder();
                componentBuilder.append("§b" + player.getName() + "向您求婚, 请谨慎做出选择: ")
                        .append("§a同意")
                        .event(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tc marry accept " + player.getName()))
                        .event(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text("§a点击原地结婚")))
                        .append("§c婉拒")
                        .event(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tc marry refuse " + player.getName()))
                        .event(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text("§c点击婉拒请求")));
                targetPlayer.spigot().sendMessage(componentBuilder.create());
                player.sendMessage("§a您已向" + targetPlayer.getName() + "发出求婚请求");
                // 存入求婚状态
                TCSP.getMarryAttr().put(player.getName(), false);
                Bukkit.getScheduler().runTaskLater(TCSP.getTcsp(), () -> {
                    // 十分钟间隔后移除维护
                    if (TCSP.getMarryAttr().get(player.getName()) != null) {
                        TCSP.getMarryAttr().remove(player.getName());
                        player.sendMessage("§c您的求婚，对方不予理睬");
                    }
                }, 20 * 60 * 10);
                itemInMainHand.setType(Material.AIR);
            }
        }
    }

    @EventHandler
    public void PlayerArmorStandManipulateEvent(PlayerArmorStandManipulateEvent event) {
        ArmorStand armorStand = event.getRightClicked();
        String customName = armorStand.getCustomName();
        Player eventPlayer = event.getPlayer();
        if (customName != null) {
            if (customName.equals("§d[至尊]§b强化大师")) {
                eventPlayer.openInventory(IntensifierPanel.getIntensifierPanel());
                event.setCancelled(true);
            } else if (customName.equals("§d[至尊]§b淬炼大师")) {
                eventPlayer.openInventory(RefinerPanel.getRefinerPanel());
                event.setCancelled(true);
            } else if (customName.equals("§d[至尊]§b等级大师")) {
                eventPlayer.openInventory(LevelerPanel.getLevelerPanel());
                event.setCancelled(true);
            }
        }
    }

    @EventHandler
    public void playerInteractEvent(PlayerInteractEvent event) {
        Player eventPlayer = event.getPlayer();
        if (!TCUtil.getAttrPlayerLRStatus(eventPlayer.getName())) {
            event.setCancelled(true);
            eventPlayer.sendMessage("§c请先登录");
            return;
        }
        // 右键空气或右键方块
        if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) {
            if (event.getItem() != null && event.getItem().getItemMeta().getDisplayName().equals("§d[Wetcland]§b小助手")) {
                eventPlayer.openInventory(TCSP.getMainMenu());
            }
        }
    }

    @EventHandler
    public void PlayerDropItemEvent(PlayerDropItemEvent event) {
        Player eventPlayer = event.getPlayer();
        ItemStack itemStack = event.getItemDrop().getItemStack();
        if (eventPlayer.getWorld().getName().equals("world")) {
            event.setCancelled(true);
            eventPlayer.sendMessage("§c主城不允许乱丢东西哦~");
            return;
        }
        if (Objects.requireNonNull(itemStack.getItemMeta()).getDisplayName().equals("§d[Wetcland]§b小助手")) {
            event.setCancelled(true);
            eventPlayer.sendMessage("§c[小助手]: 别把我抛弃~");
        }
    }

    @EventHandler
    public void PlayerCommandPreprocessEvent(PlayerCommandPreprocessEvent event) {
        System.out.println(event.getMessage());
        String message = event.getMessage();
        Player eventPlayer = event.getPlayer();
        if (!TCUtil.getAttrPlayerLRStatus(eventPlayer.getName())) {
            if (message.startsWith("/login ") || message.startsWith("/reg ")) {
            } else {
                event.setCancelled(true);
                eventPlayer.sendMessage("§c请先登录哦~");
            }
        }
    }

}
